function bclicks(obj) {
	var $first = obj.parent("td").parent("tr").children("td:first");
	var id = $first.html();
	var name = $first.next().html();
	//$("#shopName").children("option").blur();
	getParamToshopS(id, name);
}

var pagecount = 0;
var count = 0;
var shopId = "shopId";
var shopPageCount = 0;
var shopCount = 0;
var pageIndex = 1;
var htmlStr = "";
$(function() {
	$("#shopIsChoosed").click(function() {
		if ($("#shopIsChoosed").is(":checked")) {
			$("#shopName").attr("disabled", false);
		} else {
			$("#shopName").attr("disabled", true);
		}
	});
	browse('upload', 'imgSrc', 100, 100);

});

function columnSelecter(self) {
	$(self).blur();
	initSelecter({
		method : 'get',
		url : '../column/selecter',
		heads : ["columnId", "columnName"],
		titles : ["栏目Id", "栏目名称"],
		zindex : 500,
		callBack : function(response, row) {
			var value = response.getValue('columnId', row);
			var key = response.getValue('columnName', row);
			var option = $("<option value='" + value + "'>" + key + "</option>");
			$(self).empty().append($(option));
		}
	});
}

$(function() {
	refreshInput($(".serWrapper"));
});
function shopExits(id) {
	var bloo = false;
	$("#shopName").find("option").each(function() {
		if ($(this).attr("value") === id) {
			bloo = true;
			return bloo;
		}
	});
	return bloo;
}

function getParamToshopS(id, name) {
	var shopflag = $("#shopflag").val();
	var htm = "<option value='" + id + "'>" + name + "</option>";
	if (shopflag == 0) {
		$("#shopName").html("");
		$("#shopName").html(htm);
		$("#shopName").val(id);
	} else {
		$("#shopName2").html("");
		$("#shopName2").html(htm);
		$("#shopName2").val(id);
	}
	closeShopShow();
}

function closeShopShow() {
	$("#shopShow,#yinying").hide();
	$("#searchName").val("");
}

function InitShopList(shopPageIndex) {
	var shopName = $("#searchName").val();
	$.ajax({
		type : "post",
		async : false,
		data : 'name=' + shopName,
		datatype : "json",
		url : "../shop/find/shopList/" + shopPageIndex + "/5",
		success : function(data) {
			rst = JSON.parse(data);
			if (IsEmpty(rst)) {
				art.dialog({
					fixed : true,
					lock : true,
					content : "查询出错",
					icon : 'error',
					ok : true
				});
				return false;
			}
			if (rst.state == 0) {
				$("#shopList tbody tr").remove();

				initShopTable(rst);
				$("table[id='shopList'] tbody tr").each(function() {
					$(this).children("td:last").css("text-align", "center").append("<input type='button' class='common_btn' value='选择' onclick='bclicks($(this))'>");

				});
				if (rst.result.len > 0) {
					var shu = rst.result.len;
					shopCount = Math.ceil(shu / 5);
				} else {
					shopCount == 0;
				}
				$("#shopPager").pager({
					pagenumber : ++shopPageIndex,
					pagecount : shopCount,
					buttonClickCallback : ShopPageClick
				});
				addMargin($("#shopShow"));
			} else if (rst.state == 1) {
				art.dialog({
					fixed : true,
					lock : true,
					content : rst.msg,
					icon : 'error',
					ok : true
				});
			} else {
				checkStateShowErrorMsgAndDealResult(data);
			}

		}
	});
}

function InitTable(index) {
	if (IsNotEmpty(index)) {
		_pageIndex = index;
	}
	var couponName = $("#searchCouponName").val().replace(/\s/gi, '');
	//var couponFlag = $("#searchCouponFlag").val().replace(/\s/gi, '');
	var type = $("#searchType").val();
	if (type == null) {
		type = '';
	}
	var status = $("#searchStatus").val();
	var columnId = $("#searchColumn").val();
	var shopId = "";
	var param = null;
	if ($("#shopIsChoosed").is(":checked")) {
		shopId = $("#shopName").val();
		if (shopId != "" && shopId != null) {
			param = {
				'RuleName' : couponName,
				'status' : status,
				'shopId' : shopId,
				'type' : type,
				'columnId' : columnId
			};
		} else {
			param = {
				'RuleName' : couponName,
				'status' : status,
				'type' : type,
				'columnId' : columnId
			};
		}
	} else {
		param = {
			'RuleName' : couponName,
			'status' : status,
			'type' : type,
			'columnId' : columnId
		};
	}
	_ruleList = _findInfo("../couponRule/find/memberCouponRulesList/" + (_pageIndex - 1) + "/10", param);
	if (_ruleList.state == 0) {
		$("#memberList tbody tr").remove();
		loadTable(_ruleList);
		$("#sup").html("共" + _ruleList.result.len + "条");
		_loadPage("pager", _pageIndex, 10, _ruleList, InitTable, null);

	}
}

function loadTable(rst) {
	$("#memberList tbody").empty();
	for (var i = 0; i < rst.result.data.length; i++) {
		var htm = "<tr>";
		htm += "<td><img src='" + _getStringOfJson(i, rst, "imageUrl") + "'/></td>";
		htm += "<td>" + _getStringOfJson(i, rst, "ShopName") + "</td>";
		htm += "<td>" + _getStringOfJson(i, rst, "columnName") + "</td>";
		htm += "<td>" + _getStringOfJson(i, rst, "RuleName") + "</td>";
		htm += "<td>" + _getStringOfJson(i, rst, "RuleFlag") + "</td>";
		htm += "<td>" + _getStringOfJson(i, rst, "CreateFileTime") + "</td>";
		htm += "<td>" + _getStringOfJson(i, rst, "FaceValue") + "</td>";
		htm += "<td>" + _getStringOfJson(i, rst, "totalNum") + "</td>";
		htm += "<td>" + _getStringOfJson(i, rst, "usedNum") + "</td>";
		htm += "<td>" + _getStringOfJson(i, rst, "EffectDate") + "</td>";
		htm += "<td>" + _getStringOfJson(i, rst, "UneffectDate") + "</td>";
		htm += "<td>" + _getStringOfJson(i, rst, "StatusName") + "</td>";
		var id = _getIntOfJson(i, rst, "RuleID");
		htm += "<td><input class=\"common_btn \" type=\"button\" value=\"修改\"  onclick=\"toUpdate(" + id + ")\"><input class=\"del\" type=\"button\" onclick=\"popPoint(" + id + ")\" value=\"删除\"></td>";
		htm += "</tr>";
		$("#memberList tbody").append(htm);
	}
}

function toUpdate(id) {
	for (var i = 0; i < _ruleList.result.data.length; i++) {
		var ids = _getIntOfJson(i, _ruleList, "RuleID");
		if (ids == id) {
			$("#doflag").val(1);
			var shopName = _getStringOfJson(i, _ruleList, "ShopName");
			var shopId = _getStringOfJson(i, _ruleList, "ShopId");
			var status = _getStringOfJson(i, _ruleList, "Status");
			var couponName = _getStringOfJson(i, _ruleList, "RuleName");
			var couponFlag = _getStringOfJson(i, _ruleList, "RuleFlag");
			var faceValue = _getStringOfJson(i, _ruleList, "FaceValue");
			var dtBigin = _getStringOfJson(i, _ruleList, "EffectDate");
			var dtEnd = _getStringOfJson(i, _ruleList, "UneffectDate");
			var memo = _getStringOfJson(i, _ruleList, "memo");
			var indexUrl = _getStringOfJson(i, _ruleList, "indexUrl");
			var imageUrl = _getStringOfJson(i, _ruleList, "imageUrl");
			var type = _getStringOfJson(i, _ruleList, "type");
			var totalNum = _getStringOfJson(i, _ruleList, "totalNum");
			var columnId = _getStringOfJson(i, _ruleList, "columnId");
			var columnName = _getStringOfJson(i, _ruleList, "columnName");
			var columnId = _getStringOfJson(i, _ruleList, "columnId");
			var option = $("<option value='" + columnId + "'>" + columnName + "</option>");
			$("#column").empty().append($(option));

			$("#addType").val(type);
			$("#totalNum").val(totalNum);

			$("#shopName2").append("<option value='" + shopId + "'>" + shopName + "</option>");
			$("#shopName2").val(shopId);
			$("#couponName").val(couponName);
			$("#couponFlag").val(couponFlag);
			$("#dtBegin").val(dtBigin);
			$("#dtEnd").val(dtEnd);
			$("#updateId").val(id);
			$("#status").val(status);
			$("#faceValue").val(faceValue);
			$("#defaultCflag").val(couponFlag);
			$("#memo").val(memo);
			$("#indexUrl").val(indexUrl);
			$("#imageUrl").val(imageUrl);
			$("#totalNum").val(totalNum);
			$("#imgSrc img").attr("src", imageUrl);
			$("#close_this").attr("disabled", false);
		}
	}

	var dt = _findInfo("../htmlUtils/find/shophtmlStr/" + id + "/coupons", {
		"htmlUrl" : indexUrl
	});
	if (dt.state == 0) {
		editorHtml = _getStringOfJson(0, dt, "htmlStr");
	}
	$("#yinying1,#window_change").show();
}

ShopPageClick = function(pageclickednumber) {
	InitShopList(pageclickednumber - 1);
};
function search() {
	InitTable(1);
}

function search2() {
	InitShopList(0);
}

function initShopTable(json) {
	if (json != null && json.state == 0) {
		var params = new Array("id", "name", "mp", "contact");
		LoadShoptable(json, params, "shopList");
	}
}

function LoadShoptable(json, params, tableId) {
	var phArray = new Array();
	var count = 0;
	if (params != null) {
		$(params).each(function(pIndex, pData) {
			$.each(json.result.head, function(hIndex, hData) {
				if (pData == hData) {
					phArray[count++] = hIndex;
				}
			});
		});
	}
	if (json.result.data != null) {
		$.each(json.result.data, function(index, dt) {
			$("table[id='" + tableId + "']").append("<tr></tr>");
			$(phArray).each(function(phIndex, data) {
				$.each($(dt), function(dtIndex, d) {
					if (dtIndex == data) {
						$("table[id='" + tableId + "'] tr:last").append("<td>" + (d === null || d == "null" ? " " : d) + "</td>");
					}
				});
			});
		});
	}
}

function deletes(id) {
	if (IsNotEmpty(id)) {
		$.post("../couponRule/del", {
			"id" : id
		}, function(data) {
			var dt = JSON.parse(data);
			if (IsEmpty(dt)) {
				art.dialog({
					fixed : true,
					lock : true,
					content : "数据删除错误",
					icon : 'error',
					ok : true
				});
				return false;
			}
			if (dt.state == 0) {
				InitTable();
				art.dialog({
					fixed : true,
					lock : true,
					content : "删除成功",
					icon : 'succeed',
					ok : true
				});
			} else if (dt.state == 1) {
				art.dialog({
					fixed : true,
					lock : true,
					content : "数据删除错误",
					icon : 'error',
					ok : true
				});

			} else {
				checkStateShowErrorMsgAndDealResult(data);
			}
		});
	}
}

function doAddOrUpdate() {
	var flag = $("#doflag").val();
	var shopId = $("#shopName2").val();
	var couponName = $("#couponName").val();
	var couponFlag = $("#couponFlag").val();
	var faceValue = $("#faceValue").val();
	var dtBegin = $("#dtBegin").val();
	var dtEnd = $("#dtEnd").val();
	var status = $("#status").val();
	var updateId = $("#updateId").val();
	var type = $("#addType").val();
	var totalNum = $("#totalNum").val();
	var memo = $("#memo").val();

	var columnId = $("#column").val();
	if (qmsk.isEmpty(columnId)) {
		columnId = null;
	}

	var intPattern = /^[0-9]*[1-9][0-9]*$/;
	if (!intPattern.test(totalNum)) {
		artAlert("请输入正确的 券数量！");
		return;
	}

	if (!_checkMoney(faceValue, false, "面值", "faceValue") || !checkNull(couponName, "券名称", "couponName") || !checkNull(couponFlag, "券标记", "couponFlag") || !checkNull(dtBegin, "生效时间", "dtBegin") || !checkNull(dtEnd, "失效时间", "dtEnd")) {
		return false;
	}
	if (flag == 0) {
		var heads = new Array("RuleName", "columnId", "RuleFlag", "FaceValue", "EffectDate", "UneffectDate", "Status", "shopId", "RuleType", "memo", "type", "totalNum");
		var datas = new Array(couponName, columnId, couponFlag, faceValue, dtBegin, dtEnd, status, shopId, "0", memo, type, totalNum);
		var parser = new Object();
		var jsonParserStr = null;
		if (IsNotEmpty(datas)) {
			addToParser(heads, datas, "add", parser);
			jsonParserStr = JSON.stringify(parser);
		}
		addRebateRules(jsonParserStr);

	} else {
		var heads = new Array("RuleName", "columnId", "RuleFlag", "FaceValue", "EffectDate", "UneffectDate", "Status", "shopId", "RuleType", "memo", "type", "totalNum", "id");
		var datas = new Array(couponName, columnId, couponFlag, faceValue, dtBegin, dtEnd, status, shopId, "0", memo, type, totalNum, updateId);
		var parser = new Object();
		var jsonParserStr = null;
		if (IsNotEmpty(datas)) {
			addToParser(heads, datas, "edit", parser);
			jsonParserStr = JSON.stringify(parser);
		}
		updatRebateRules(jsonParserStr, updateId);
	}
}

function addRebateRules(jsonParserStr) {
	$("#close_this").attr("disabled", true);

	if (IsEmpty(shopId)) {
		art.dialog({
			fixed : true,
			lock : true,
			content : "请选择店铺",
			icon : 'error',
			ok : true
		});

		$("#shopName2").html("请选择店铺");

		return false;
	}
	var dt = _insertInfoNoSucceedMessage("../couponRule/insert", {
		"data" : jsonParserStr,
		"html" : editorHtml
	});
	if (dt.state == 0) {
		upload(_getIntOfJson(0, dt, "id"));
	}
}

function upload(id) {
	$.ajaxFileUpload({
		url : "../couponRule/upload/image/" + id,
		secureuri : false,
		fileElementId : 'upload',
		dataType : 'json',
		success : function(data) {
			if (IsEmpty(data)) {
				art.dialog({
					fixed : false,
					lock : true,
					content : "上传图片出错",
					icon : 'error',
					ok : true
				});
				return false;
			}
			if (data.state == 0) {

				art.dialog({
					fixed : false,
					lock : true,
					content : "操作成功",
					icon : 'succeed',
					ok : true
				});
				InitTable(1);
				$("#yinying1,#window_change").hide();
				browse('upload', 'imgSrc', 100, 100);

			} else if (data.state == 1) {
				art.dialog({
					fixed : false,
					lock : true,
					content : "保存图片出错,请重新上传图片",
					icon : 'error',
					ok : true
				});
			} else {
				checkStateShowErrorMsgAndDealResult(data);
			}

		},
		error : function(data) {
			art.dialog({
				fixed : true,
				lock : true,
				content : '上传图片失败',
				icon : 'error',
				ok : true
			});
			return false;
		}
	});
}

function updatRebateRules(jsonParserStr, id) {
	$("#close_this").attr("disabled", true);

	var dt = _insertInfoNoSucceedMessage("../couponRule/edit", {
		"data" : jsonParserStr,
		"html" : editorHtml
	});
	if (dt.state == 0) {
		if (IsEmpty($("#upload").val())) {
			art.dialog({
				fixed : true,
				lock : true,
				content : "修改成功",
				icon : 'succeed',
				ok : true
			});
			InitTable(null);
			$("#yinying1,#window_change").hide();
		} else {
			upload(id);
		}
	}
}

function showShopList(flag) {
	$("#shopflag").val(flag);
	if (flag == 0) {

		$("#shopIsChoosed").attr("checked", "checked");
		$("#shopName").blur();
	} else {
		$("#shopName2").blur();

	}
	$("#shopShow,#yinying").show();
	addMargin($("#shopShow"));
	InitShopList(0);
}

function popPoint(id) {
	art.dialog({
		fixed : true,
		lock : true,
		content : "确认删除该条数据？",
		icon : 'question',
		ok : function() {
			deletes(id);
		},
		cancel : true
	});
}

function resetForm() {
	$("#couponName").val("");
	$("#couponFlag").val("");
	$("#dtBegin").val("");
	$("#dtEnd").val("");
	$("#shopName2").html("");
	$("#yinying1,#window_change").show();
	$("#close_this").val("保存");
	$("#close_this").attr("disabled", false);
	$("#faceValue").val("");
	$("#memo").val("");
	$("#indexUrl").val("");
	$("#imageUrl").val("");
}

$(function() {
	$("#addColumn").click(function() {
		resetForm();
		$("#doflag").val(0);
	});
	addMargin($("#window_change"));
	$("#memberList tbody tr").each(function() {

		$(this).children("td:last").children("input").eq(0).click(function() {

			$("#yinying1,#window_change").show();
		});
	});
	$("#closeThe").click(function() {
		$("#yinying1,#window_change").hide();
	});
});
